import { _decorator, Camera, CCFloat, Component, EventTouch, Input, input, Layers, Node, PhysicsSystem2D, v2, v3, Vec2 } from 'cc';
import { EventManager, } from '../event/EventManager';
const { ccclass, property } = _decorator;

@ccclass('TowerCamera')
export class TowerCamera extends Component {

    public static instance: TowerCamera;

    private touchStartTime: number = 0
    protected onLoad(): void {
        TowerCamera.instance = this
    }


    public speed: number = 1;
    public camera: Camera;

    start() {
        this.camera = this.node.getComponent(Camera)

        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    protected onDisable(): void {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    onTouchStart() {
       
    }

    onTouchMove(event: EventTouch) {
        let touches = event.getAllTouches()
        if (touches.length == 1) {
            let pre = event.getPreviousLocation()
            let now = v2(event.getLocationX(), event.getLocationY())
            let offset = v2(0, 0)
            Vec2.subtract(offset, now, pre)

            this.speed = this.camera.orthoHeight * (1 / 700)

            this.node.translate(v3(- offset.x * this.speed, -offset.y * this.speed, 0))

          
        } else {
            let a = touches[0]
            let b = touches[1]
            let preDistance = Vec2.distance(a.getPreviousLocation(), b.getPreviousLocation())

            let nowDistance = Vec2.distance(a.getLocation(), b.getLocation())

            let orthoHeight = 0

            if (preDistance == nowDistance) {
                return
            }
            if (preDistance > nowDistance) {

                //放大
                orthoHeight = this.camera.orthoHeight + this.camera.orthoHeight * (10 / 700)
            } else {

                //缩小
                orthoHeight = this.camera.orthoHeight - this.camera.orthoHeight * (10 / 700)
            }

            if (orthoHeight < 350) {
                orthoHeight = 350
            }
            if (orthoHeight > 1400) {
                orthoHeight = 1400
            }
            this.camera.orthoHeight = orthoHeight

        }

    }

    onTouchEnd(event: EventTouch) { 
    }


}


